from django.views import View
import json
from django.http.response import JsonResponse
from django_redis import get_redis_connection

from utils.response_code import RET
from homes.models import House
import logging
from order.models import Order

logger = logging.getLogger('django')


class OrderView(View):
    """订单"""

    def post(self, request):
        """添加订单"""

    # 接受参数
        user = request.user
        dict_data = json.loads(request.body.decode())  # 获取前端发送的数据

        house_id = dict_data.get('house_id')
        start_date = dict_data.get('start_date')
        end_date = dict_data.get('end_date')

    # 校验参数,核心逻辑(判断房间是否存在，是否没别预定),返回响应
        if not all(['house_id', 'start_date', 'end_date']):
            return JsonResponse({'error': RET.PARAMERR, 'errmsg': '缺少必传参数'})

        # 查询房间是否存在
        try:
            house = House.objects.get(id=house_id)
        except Exception as e:
            logger.error(e)
            return JsonResponse({'error': RET.NODATA, 'errmsg': '房屋不存在'})

        # 判断房屋是否属于用户个人
        if user.id == house.user.id:
            return JsonResponse({'error': RET.ROLEERR, 'errmsg': '不符合订购标准'})

        # 判断房间是否为空
        try:
            count = Order.objects.filter(house=house, end_date__gte=start_date, begin_date__lt=end_date).count()
        except Exception as e:
            logger.error(e)
            return JsonResponse({'error': RET.DBERR, 'errmsg': '数据库查询错误'})
        days = (end_date - start_date).days
        if count == 0:
            order = Order.objects.create(
                user=user,
                house=house,
                begin_date=start_date,
                end_date=end_date,
                days=days,
                house_price=house.price,
                amount=days * house.price
            )
            return JsonResponse({'errno': RET.OK, 'errmsg': '下单成功', 'order_id': order.id})
        else:
            return JsonResponse({'error': RET.DATAERR, 'errmsg': '房间别预定了'})

    def get(self, request):
        """获取订单"""

        # 接受参数
        user = request.user
        role = request.GET.get('role')

        # 校验参数
        if not role:
            return JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        # 判断下数据是否正确
        if role not in ['custom', 'landlord']:
            return JsonResponse({"errno": RET.PARAMERR, "errmsg": "参数错误"})

        # # 判断是否是房东
        # if role =='custom':
        #
        # # 构造数据
        # order_list = []
        #
        # #　响应结果
        # return JsonResponse({
        #     "errno": RET.OK,
        #     "errmsg": '发布成功',
        #     "data": {"orders": order_list}
        # })
        if role == "custom":
            # 查询当前自己下了哪些订单
            orders = Order.objects.filter(user=user).order_by("-create_time")
        else:
            # 查询自己房屋都有哪些订单
            houses = House.objects.filter(user=user)
            house_ids = [house.id for house in houses]
            orders = Order.objects.filter(house_id__in=house_ids).order_by("-create_time")

        orders_dict = [order.to_dict() for order in orders]
        print(orders_dict)
        return JsonResponse({"errno": RET.OK, "errmsg": "发布成功", "data": {"orders": orders_dict}})


class OrderStatusView(View):
    """接单和拒单"""

    def put(self, request, order_id):

        # 接受参数
        user = request.user
        dict_data = json.loads(request.body.decode())
        action = dict_data.get('action')

        # 校验参数
        if action not in ['accept', 'reject']:
            return JsonResponse({'error': RET.PARAMERR, 'errmsg': '参数错误'})

        # 核心逻辑
        try:
            order = Order.objects.filter(id=order_id, status=Order.ORDER_STATUS['WAIT_ACCEPT'])
            house = order.house
        except Exception as e:
            logger.error(e)
            return JsonResponse({'error': RET.DBERR, 'errmsg': '查询的数据有误'})

        # 判断订单是否存在并且当前房屋的用户id是当前用户的id(没想过)
        if not order or house.user != user:
            return JsonResponse({"errno": RET.NODATA, "errmsg": "数据有误"})

        if action == 'accept':
            # 接单
            order.status = Order.ORDER_STATUS['WAIT_COMMENT']
        elif action == 'reject':
            # 获取拒单原因
            reason = dict_data.get('reason')
            if not reason:
                return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '未填写拒绝原因'})
            order.status = Order.ORDER_STATUS['REJECTED']
            order.comment = reason

        # 响应结果
        order.save()
        return JsonResponse({'errno': RET.OK, 'errmsg': 'ok'})


class OrderCommentView(View):
    """订单评价"""

    def put(self, request, order_id):

        # 接受参数
        dict_data = json.loads(request.body.decode())
        comment = dict_data.get('comment')

        # 校验参数
        if not comment:
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': "请输入评论内容"})

        order = Order.objects.filter(id=order_id, status=Order.ORDER_STATUS["WAIT_COMMENT"])
        house = order.house

        # 更新数据
        house.order_count += 1
        order.status = Order.ORDER_STATUS["COMPLETE"]
        order.comment = comment

        # 更新数据库
        house.save()
        order.save()
        redis_conn = get_redis_connection("house_cache")
        try:
            redis_conn.delete('house_info_' + str(house.id))
        except Exception as e:
            logging.error(e)

        # 返回响应
        return JsonResponse({'errno': RET.OK, 'errmsg': 'ok'})